#include "RCHTTPClient.h"


RCHTTPClient::RCHTTPClient(void)
{
}

RCHTTPClient::RCHTTPClient(std::string host, int port)
{
	Host = host;
	Port = port;

	WSADATA info; 
	WSAStartup(MAKEWORD(2,0), &info);

	thisSocket = socket(AF_INET,SOCK_STREAM,0);

	std::string error;

	hostent *he;
	if ((he = gethostbyname(Host.c_str())) == 0) 
	{
		error = strerror(errno);
		throw error;
	}

	sockaddr_in addr;
	  addr.sin_family = AF_INET;
	  addr.sin_port = htons(Port);
	  addr.sin_addr = *((in_addr *)he->h_addr);
	  memset(&(addr.sin_zero), 0, 8); 

	  if (connect(thisSocket, (sockaddr *) &addr, sizeof(sockaddr))) 
	  {
		error = strerror(WSAGetLastError());
		throw error;
	  }
}


RCHTTPClient::~RCHTTPClient(void)
{
	WSACleanup();
}

std::string RCHTTPClient::GetHost()
{
	return Host;
}
int RCHTTPClient::GetPort()
{
	return Port;
}

void RCHTTPClient::SendLine (std::string msg)
{
	msg += "\n";
	send(thisSocket,msg.c_str(),msg.length(),0);
}

std::string RCHTTPClient::ReceiveLine()
{
	std::string ret;

	while (1) {
    char r;

    switch(recv(thisSocket, &r, 1, 0)) 
	{
      case 0: 
        return ret;
      case -1:
        return "";
    }

    ret += r;
    if (r == '\n')  
		return ret;
  }
}

std::string RCHTTPClient::GetPage(std::string url)
{
	std::string page;

	url = "GET /" + url + " HTTP/1.0";
	SendLine(url);
	SendLine("Host: " + Host);
	SendLine("");
	
	while(1)
	{
		std::string line = ReceiveLine();

		if(line.empty())
			break;
		else

		page += line;
	}

	return page;
}